package user.fragment;

import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;
import java.util.List;

import com.example.xfengshopping.R;
import user.fragment.OrderDetailActivity;

public class OrderAdapter extends RecyclerView.Adapter<OrderAdapter.OrderViewHolder> {

    private final ArrayList<OrderItem> orderItems;

    public OrderAdapter(ArrayList<user.fragment.OrderItem> orderItems) {
        this.orderItems = orderItems;
    }

    @NonNull
    @Override
    public OrderViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_order, parent, false);
        return new OrderViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull OrderViewHolder holder, int position) {
        OrderItem item = orderItems.get(position);

        holder.tvOrderNo.setText("订单号: " + item.getOrderNo());
        holder.tvStatus.setText("状态: " + item.getOrderStatusString());
        holder.tvTotalPrice.setText("总价: ¥" + item.getTotalPrice());

        OrderGoodsAdapter goodsAdapter = new OrderGoodsAdapter(item.getGoodsItems());
        holder.recyclerViewGoods.setLayoutManager(new LinearLayoutManager(holder.itemView.getContext()));
        holder.recyclerViewGoods.setAdapter(goodsAdapter);

        // 点击订单跳转到订单详情页
        holder.itemView.setOnClickListener(v -> {
            Context context = v.getContext();
            Intent intent = new Intent(context, OrderDetailActivity.class);
            intent.putExtra("orderNo", item.getOrderNo());
            context.startActivity(intent);
        });
    }

    @Override
    public int getItemCount() {
        return orderItems.size();
    }

    static class OrderViewHolder extends RecyclerView.ViewHolder {
        TextView tvOrderNo;
        TextView tvStatus;
        TextView tvTotalPrice;
        RecyclerView recyclerViewGoods;

        public OrderViewHolder(@NonNull View itemView) {
            super(itemView);
            tvOrderNo = itemView.findViewById(R.id.tvOrderNo);
            tvStatus = itemView.findViewById(R.id.tvStatus);
            tvTotalPrice = itemView.findViewById(R.id.tvTotalPrice);
            recyclerViewGoods = itemView.findViewById(R.id.recyclerViewGoods);
        }
    }
}
